<template>
  <div class="import-panel">
    <div class="panel-header mb-4">
      <h3 class="text-lg font-bold">{{ title }}</h3>
    </div>
    
    <div class="panel-content">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="upload-area">
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              :show-file-list="true"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :limit="1"
              accept=".xlsx,.xls,.csv"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </el-upload>
            
            <div class="action-buttons mt-4 flex justify-center">
              <el-button 
                type="primary" 
                @click="handleImport" 
                :loading="importLoading"
                :disabled="!selectedFile"
                class="import-btn"
              >
                <el-icon class="mr-1"><Upload /></el-icon>开始导入
              </el-button>
              <el-button 
                type="info" 
                @click="downloadTemplate"
                class="template-btn ml-2"
              >
                <el-icon class="mr-1"><Download /></el-icon>下载模板
              </el-button>
            </div>
          </div>
        </el-col>
        
        <el-col :span="12">
          <div class="import-guide">
            <h4 class="text-md font-bold mb-2">导入说明</h4>
            <ul class="guide-list text-gray-500">
              <li v-for="(item, index) in description" :key="index" class="mb-1">
                <el-icon class="text-primary mr-1"><InfoFilled /></el-icon>{{ item }}
              </li>
            </ul>
            
            <el-divider content-position="center">导入流程</el-divider>
            
            <el-steps :active="activeStep" finish-status="success" simple>
              <el-step title="下载模板" />
              <el-step title="填写数据" />
              <el-step title="上传文件" />
              <el-step title="开始导入" />
            </el-steps>
          </div>
        </el-col>
      </el-row>
      
      <!-- 导入结果 -->
      <div v-if="importResult.visible" class="import-result mt-4">
        <el-alert
          :title="importResult.title"
          :type="importResult.type"
          :description="importResult.description"
          show-icon
        />
        
        <div v-if="importResult.showDetail && importResult.detail" class="result-detail mt-2">
          <el-collapse>
            <el-collapse-item title="导入详情" name="1">
              <div class="p-3">
                <p>总数据：{{ importResult.detail.total }} 条</p>
                <p>成功数：{{ importResult.detail.success }} 条</p>
                <p>失败数：{{ importResult.detail.fail }} 条</p>
                <el-button 
                  v-if="importResult.detail.fail > 0"
                  type="primary" 
                  size="small" 
                  @click="downloadFailResult"
                  class="mt-2"
                >
                  下载失败明细
                </el-button>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Download, Upload, InfoFilled } from '@element-plus/icons-vue'

export default {
  name: 'ImportPanel',
  components: {
    UploadFilled,
    Download,
    Upload,
    InfoFilled
  },
  props: {
    title: {
      type: String,
      default: '数据导入'
    },
    description: {
      type: Array,
      default: () => []
    },
    templateUrl: {
      type: String,
      default: ''
    },
    importUrl: {
      type: String,
      default: ''
    }
  },
  emits: ['success'],
  setup(props, { emit }) {
    const selectedFile = ref(null)
    const importLoading = ref(false)
    const activeStep = ref(1)
    
    // 导入结果
    const importResult = reactive({
      visible: false,
      type: 'success',
      title: '',
      description: '',
      showDetail: false,
      detail: null
    })
    
    // 处理文件选择
    const handleFileChange = (file) => {
      selectedFile.value = file
      activeStep.value = 3
      
      // 检查文件类型
      const validTypes = ['.xlsx', '.xls', '.csv']
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      if (!validTypes.includes(fileExt)) {
        ElMessage.warning('请上传正确的文件格式：Excel或CSV文件')
        selectedFile.value = null
        return false
      }
      
      // 检查文件大小，限制为10MB
      const maxSize = 10 * 1024 * 1024 // 10MB
      if (file.size > maxSize) {
        ElMessage.warning('文件大小不能超过10MB')
        selectedFile.value = null
        return false
      }
      
      return true
    }
    
    // 处理文件移除
    const handleFileRemove = () => {
      selectedFile.value = null
      activeStep.value = 1
    }
    
    // 下载模板
    const downloadTemplate = () => {
      if (!props.templateUrl) {
        ElMessage.warning('模板下载地址未配置')
        return
      }
      
      ElMessage.success('模板下载成功')
      activeStep.value = 2
      // 实际项目中应调用下载API
      // window.location.href = props.templateUrl
    }
    
    // 开始导入
    const handleImport = async () => {
      if (!selectedFile.value) {
        ElMessage.warning('请先选择要导入的文件')
        return
      }
      
      if (!props.importUrl) {
        ElMessage.warning('导入接口未配置')
        return
      }
      
      importLoading.value = true
      // 重置导入结果
      importResult.visible = false
      
      try {
        // 实际项目中应调用导入API
        /*
        const formData = new FormData()
        formData.append('file', selectedFile.value.raw)
        const { data } = await axios.post(props.importUrl, formData)
        */
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 模拟导入成功
        activeStep.value = 4
        importResult.visible = true
        importResult.type = 'success'
        importResult.title = '导入成功'
        importResult.description = '数据已成功导入系统'
        importResult.showDetail = true
        importResult.detail = {
          total: 100,
          success: 98,
          fail: 2
        }
        
        // 触发成功事件
        emit('success')
      } catch (error) {
        // 导入失败
        importResult.visible = true
        importResult.type = 'error'
        importResult.title = '导入失败'
        importResult.description = '导入过程中发生错误，请检查文件格式或联系管理员'
        console.error('导入失败:', error)
      } finally {
        importLoading.value = false
      }
    }
    
    // 下载失败明细
    const downloadFailResult = () => {
      ElMessage.success('失败明细下载成功')
      // 实际项目中应调用下载API
      // window.location.href = '/api/import/fail-detail'
    }
    
    return {
      selectedFile,
      importLoading,
      activeStep,
      importResult,
      handleFileChange,
      handleFileRemove,
      downloadTemplate,
      handleImport,
      downloadFailResult
    }
  }
}
</script>

<style scoped>
.import-panel {
  padding: 16px 0;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.import-guide {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  height: 100%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.import-guide:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.guide-list {
  list-style: none;
  padding-left: 0;
  margin-bottom: 16px;
}

.guide-list li {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  transition: all 0.3s;
  padding: 6px 0;
  border-radius: 4px;
}

.guide-list li:hover {
  background-color: rgba(64, 158, 255, 0.1);
  padding-left: 8px;
  transform: translateX(4px);
}

.import-btn, .template-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.import-btn:hover, .template-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.result-detail {
  margin-top: 16px;
}

/* 上传区域样式优化 */
:deep(.el-upload-dragger) {
  transition: all 0.3s;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
}

:deep(.el-upload-dragger:hover) {
  border-color: var(--el-color-primary);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-upload__text) {
  margin-top: 12px;
}

:deep(.el-upload__text em) {
  color: var(--el-color-primary);
  font-style: normal;
  font-weight: bold;
}

/* 步骤条样式 */
:deep(.el-steps) {
  margin-top: 20px;
}

:deep(.el-step__title) {
  font-size: 14px;
}

:deep(.el-step__head.is-process), 
:deep(.el-step__head.is-finish) {
  transition: all 0.3s;
}

:deep(.el-step__head.is-finish:hover) {
  transform: scale(1.1);
}

/* 警告框样式 */
:deep(.el-alert) {
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.el-alert:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 折叠面板样式 */
:deep(.el-collapse-item__header) {
  font-weight: bold;
  transition: all 0.3s;
}

:deep(.el-collapse-item__header:hover) {
  color: var(--el-color-primary);
  transform: translateY(-1px);
}

/* 暗黑模式适配 */
:deep(.dark-theme .import-guide) {
  background-color: #2a2a2a;
}

:deep(.dark-theme .guide-list li:hover) {
  background-color: rgba(64, 158, 255, 0.05);
}

:deep(.dark-theme .el-upload-dragger) {
  border-color: #4c4d4f;
  background-color: #2c2d2f;
}

:deep(.dark-theme .el-upload-dragger:hover) {
  border-color: var(--el-color-primary);
}
</style> 